package com.jzrh.flashbee.controller;

import com.jzrh.flashbee.common.core.exception.ParamException;
import com.jzrh.flashbee.common.utils.Result;
import com.jzrh.flashbee.entity.dto.LoginDTO;
import com.jzrh.flashbee.service.IFlashbeeUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author Jince
 * @since: 2023.11.23 上午 12:19
 * @description:
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class UserController {
    @Resource
    private IFlashbeeUserService flashbeeUserService;

    /**
     * 生成密钥
     */
    @GetMapping("/getAccessKey")
    public Result<Map<String, String>> getAuthAccessKey(String username) {
        return Result.success("密钥生成成功", flashbeeUserService.generateAccessKey(username));
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO, HttpServletRequest request){
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(request.getRemoteAddr());
        if(attribute==null){
            Boolean login = flashbeeUserService.login(loginDTO, request);
            if(login){
                return Result.success("登录成功");
            }
            return Result.error("登录失败");
        }
        return Result.success("你已登录");
    }
}
